<template>
  <div class="home-container">
    <!--  TODO 跳转的逻辑还没做完 -->
    <el-row>
      <el-col :span="12">
        <el-autocomplete v-model="state4" :fetch-suggestions="querySearchAsync" placeholder="请输入内容"
          @select="handleSelect">
          <el-button slot="append" icon="el-icon-search" @click="searchHandler"></el-button>
        </el-autocomplete>
      </el-col>
      <el-col :span="12">
        <div @click="tagHandler">
          <el-tag v-for="(tag, index) in tags" :key="index" :data-index="index" size="small"
            class="tag-sty">{{ tag }}</el-tag>
        </div>
      </el-col>
    </el-row>
    <el-table v-loading="loading" :data="listData" style="width: 100%">
      <el-table-column prop="name" label="名称" width="180"></el-table-column>
      <el-table-column prop="alis" label="别名" width="180"></el-table-column>
      <el-table-column prop="type" label="类型" width="180"></el-table-column>
      <el-table-column prop="console" label="生成代码" width="180"></el-table-column>
      <el-table-column label="操作">
        <template slot-scope="scope">
          <el-button size="mini" type="danger" @click="toChange(scope.row)">修改</el-button>
        </template>
      </el-table-column>
    </el-table>
  </div>
</template>

<script>
export default {
  name: "home",
  data() {
    return {
      state4: "",
      tags: [],
      tips: [],
      listData: [],
      loading: false
    };
  },
  created() {
    if (localStorage.getItem("tags")) {
      this.tags = localStorage.getItem("tags").split(",") || [];
    }
  },
  methods: {
    /**
     * 修改路由跳转
     * */
    toChange(row) {
      let { type, _id } = row;
      let hashMap = {
        foods: "/recipeAddOrEdit",
        materials: "/techAddOrEdit",
        anims: "/animal-add-or-edit",
        natures: "/NatureAddOrEdit",
        heros: "/heroUpdate"
      };
      this.$router.push({
        path: hashMap[type],
        query: {
          id: _id,
          type: "edit"
        }
      });
    },
    /**
     * 历史记录标签点击事件
     * */
    tagHandler(e) {
      let dom = e.target;
      let index = dom.getAttribute("data-index");
      this.state4 = this.tags[parseInt(index)];
      this.search(this.state4);
    },
    searchHandler() {
      this.search(this.state4);
    },
    /**
     * 搜索
     * */
    search(inputVal) {
      if (!inputVal) {
        return;
      }
      this.loading = true;
      this.saveTag(inputVal);
      this.axios
        .get("/search", {
          params: {
            version: this.$store.state.version,
            searchVal: inputVal,
            module: [
              "materials",
              "foods",
              "anims",
              "natures",
              "heros",
              "geographys"
            ]
          }
        })
        .then(res => {
          let temp = res.data.reduce(function (sum, current) {
            let arr = current.list.map(val => {
              return {
                ...val,
                type: current.type
              };
            });
            return sum.concat(arr);
          }, []);
          this.listData = temp;
          this.loading = false;
        });
    },
    /**
     * 用户输入时给出搜索建议
     * */
    querySearchAsync(queryString, cb) {
      if (!queryString) {
        return;
      }
      this.axios
        .get("/search/tip", {
          params: {
            version: this.$store.state.version,
            inputVal: queryString,
            module: [
              "materials",
              "foods",
              "anims",
              "natures",
              "heros",
              "geographys"
            ]
          }
        })
        .then(res => {
          let result = this.creatResult(res.data);
          console.log(result, "sss");
          cb(result);
        });
    },
    /**
     * @description 转化成需要的json arr
     *
     * */
    creatResult(arr = []) {
      if (arr.length === 0) {
        return;
      }
      let list = [];
      for (let val of arr) {
        list = [...list, ...val.list];
      }
      return list.map(val => {
        return {
          value: val.name
        };
      });
    },
    /**
     * 建议项点击事件
     * */
    handleSelect() {
      this.saveTag(this.state4);
      this.search(this.state4);
    },
    /**
     * 保存tag
     * @param val
     */
    saveTag(val) {
      // 判断是否存在相同的标签，如果存在则不保存
      let isFind = this.tags.some(item => {
        return item === val;
      });
      if (isFind) {
        return;
      }
      this.tags.push(val);
      let _tagString = this.tags.join(",");
      localStorage.setItem("tags", _tagString);
    }
  }
};
</script>
<style lang="scss">
.home-container {
  .el-input__inner {
    min-width: 180px;
  }
}
</style>
<style lang="scss" scoped>
.home-container {
  padding: 16px;
  overflow: hidden;

  .tag-sty {
    margin-left: 12px;
    margin-bottom: 12px;
    cursor: pointer;
  }
}
</style>
